package com.kuanter.kuanterauto.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.view.View;
import android.view.View.MeasureSpec;

public class DrawNumber {
	private Activity activity;

	public DrawNumber(Activity activity) {
		super();
		this.activity = activity;
	}

	/**
	 * 在给定的图片上加上数量。
	 * 
	 * @param icon
	 *            给定的图片
	 * @return 带数量的图片
	 */
	public Bitmap generatorContactCountIcon(Bitmap icon,int number) {
		// 初始化画布
		/*int iconSize = (int) activity.getResources().getDimension(
				android.R.dimen.app_icon_size);*/
		Bitmap contactIcon = Bitmap.createBitmap(icon);
//				Config.ARGB_8888);
		Canvas canvas = new Canvas(contactIcon);
		// 拷贝图片
		Paint iconPaint = new Paint();
		iconPaint.setDither(true);// 防抖动
		iconPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理，这样，当你选择Drawable时，会有抗锯齿的效果
		Rect src = new Rect(0, 0, icon.getWidth(), icon.getHeight());
		Rect dst = new Rect(0, 0, icon.getWidth(), icon.getHeight());
		canvas.drawBitmap(icon, null, dst, iconPaint);
		// 启用抗锯齿和使用设备的文本字距
		Paint countPaint = new Paint(Paint.ANTI_ALIAS_FLAG
				| Paint.DEV_KERN_TEXT_FLAG);
		countPaint.setColor(Color.WHITE);
		countPaint.setTextSize(18f);
		countPaint.setTypeface(Typeface.DEFAULT_BOLD);
		// 在图片上创建一个覆盖的个数
		String numberStr = String.valueOf(number);
		if(numberStr.length() == 1){
			canvas.drawText(numberStr, icon.getWidth()/2-5, icon.getHeight()/2+4,countPaint);
		}else if(numberStr.length() == 2){
			canvas.drawText(numberStr, icon.getWidth()/2-10, icon.getHeight()/2+4,countPaint);
		}else if(numberStr.length() == 3){
			canvas.drawText(numberStr, icon.getWidth()/2-15, icon.getHeight()/2+4,countPaint);
		}
		return contactIcon;
	}

	public Bitmap convertViewToBitmap(View view) {
		view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
		view.buildDrawingCache();
		Bitmap bitmap = view.getDrawingCache();
		return bitmap;
	}

}
